package com.bilibili.juc.arthas;

/**
 * 二分查找法
 */
public class BinarySearch {
    public static void main(String[] args) {
//        int[] arr = {1, 2, 3, 4,5,6,7,8,9,10,16,17};

                   // 0 1  2  3 4 5 6 7 8 9  10  11
        int[] arr = {7, 23, 79, 81,103,127,131,147};
        //           0   1   2   3  4   5   6   7
        int searchEle = 131;
        int index = search(0, arr.length - 1, searchEle, arr);
        System.out.println(index);

        int i = binarySearch(searchEle, arr);
        System.out.println(i);

        int j = binarySearchHigh(searchEle, arr);
        System.out.println(j);
    }

    public static int binarySearchHigh(int searchEle, int[] arr){
        int left = 0;
        int right = arr.length-1;
        //如果查询的值不在这个区间，为了性能直接返回-1
        if (searchEle < arr[left] || searchEle > arr[right]){
            return -1;
        }
        int middle;
        while (left <= right){
            middle = (left+right)/2;
            if (searchEle > arr[middle]){
                left= middle+1;
            } else if (searchEle < arr[middle]){
                right=middle-1;
            }else {
                return middle;
            }

        }

        return -1;
    }
    public static int binarySearch(int searchEle, int[] arr){
        int left = 0;
        int right = arr.length-1;
        int middle;
        while (left <= right){
            middle = (left+right)/2;
            if (searchEle > arr[middle]){
                left= middle+1;
            } else if (searchEle < arr[middle]){
                right=middle-1;
            }else {
                return middle;
            }

        }

        return -1;
    }

    public static int search(int left, int right, int searchEle, int[] arr){
        if (left > right){
            return -1;
        }
        int mid = (left+right)/2;
        if (searchEle > arr[mid]){
            return search(mid+1,right,searchEle,arr);
        }else if (searchEle < arr[mid]){
            return search(left,mid-1,searchEle,arr);
        }
        return mid;
    }
}
